package com.dao.impl;

import com.dao.GoodsDao;
import com.dao.GoodsForOrderinfoDao;
import com.entity.Goods;
import com.entity.GoodsExample;
import com.mapper.GoodsMapper;
import com.page.PageInfo;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class GoodsDaoImpl implements GoodsDao, GoodsForOrderinfoDao {
    @Resource
    GoodsMapper goodsMapper;

    /**
     * 根据管理员编号查询一个管理员
     * @param gid  管理员编号
     * @return 管理员对象
     */
    public Goods getByGid(String gid){
        return goodsMapper.selectByPrimaryKey(gid);
    }
    public List<Goods> getAll(){
        return goodsMapper.getAll();
    }
    public List<Goods> getAllByPage(PageInfo pageInfo){
        int currPage = pageInfo.getCurrPage();
        int pageSize = pageInfo.getPageSize();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("currPage", currPage);
        map.put("pageSize", pageSize);
        System.out.println(pageInfo.getCurrPage() + " "+ pageInfo.getPageSize());
        //调用示例查询得到当前的总记录数
        pageInfo.setItemCount((int) goodsMapper.countByExample(new GoodsExample()));
        return goodsMapper.getAllByPage(map);
    }

    @Override
    public List<Goods> searchNameByPage(PageInfo pageInfo,String key) {

        GoodsExample goodsExample = new GoodsExample();
        int limit = pageInfo.getPageSize();
        int offset = (pageInfo.getCurrPage() - 1) * limit;
        goodsExample.setOffset(offset);//就是原来的firstResult 就是通过（currPage - 1） * pageSize
        goodsExample.setLimit(limit);
        //createCriteria 创建一个条件查询
        goodsExample.createCriteria().andGnameLike(key);
        goodsExample.or(goodsExample.createCriteria().andGdescLike(key));
        return goodsMapper.selectByExample(goodsExample);
    }

    /**
     * 根据主键查询
     * @param gid
     * @return
     */
    public Goods getGoodsByGid(String gid){
        return goodsMapper.selectByPrimaryKey(gid);
    }

    /**
     * 添加一个实体
     * @param goods
     * @return
     */
    public int addGoods(Goods goods){
        return goodsMapper.insertSelective(goods);
    }
    /**
     * 修改实体,如果有条件 需要设置example
     */
    public int updateGoods(Goods goods){
        return goodsMapper.updateByPrimaryKeySelective(goods);
    }
    public int updateGoodsByExample(Goods goods){
        return goodsMapper.updateByExample(goods,null);
    }

    /**
     * 删除一个实体
     * @param gid
     * @return
     */
    public int deleteGoodsByPrimayKey(String gid){
        return goodsMapper.deleteByPrimaryKey(gid);
    }

    /**
     * 删除实体根据示例
     * @return
     */
    public int deleteGoodsByExample(){
        return goodsMapper.deleteByExample(null);
    }

//根据商品编号数组字符串查询 多个商品到购物车
    public List<Goods> getByGtids(String gids){
        return  goodsMapper.getByGtids(gids);
    }


}
